<template>
    <div ref="chartContainer" style="width: 100%; height: 400px;"></div>
  </template>
  
  <script setup lang="ts">
  import { ref, onMounted, onUnmounted, watch,onUpdated} from 'vue';
  import * as echarts from 'echarts';
  import { arrayToLineEchart } from '../../utils/fmtData';
  const chartContainer = ref<HTMLDivElement | null>(null);
  let chartInstance: echarts.ECharts | null = null;
  onMounted(() => {
    if (chartContainer.value) {
      chartInstance = echarts.init(chartContainer.value);

      setChartOptions();
      window.addEventListener('resize', resizeChart);
    }
  });
  
  onUnmounted(() => {
    if (chartInstance) {
      chartInstance.dispose();
      window.removeEventListener('resize', resizeChart);
    }
  });
  const props = defineProps({
    title: {
      type: String,
      default: null,
    },
    legend: {
      type: Array,
      default: undefined,
    }, 
    xAxis: {
      type: Array,
      default: undefined,
    },
    series: {
      type: Array,
      default: undefined,
    },
  })
  const setChartOptions = () => {
    const option = {
      title: {
          text: props.title
        },
        tooltip: {
          trigger: 'axis'
        },
        legend: {
          data: props.legend
        },
        xAxis: {
          data: props.xAxis
        },
        yAxis: {
        },
        series: props.series
    };
  
    if (chartInstance) {
      chartInstance.setOption(option);
    }
  };
  
  const resizeChart = () => {
    if (chartInstance) {
      chartInstance.resize();
    }
  };

  defineExpose({  
    resizeChart  
  }); 

  watch(  
    () => props, // 监听 array 的变化  
    (newVal, oldVal) => {
      setChartOptions()
      resizeChart()
      // 在这里执行你需要的操作  
    },  
    { deep: true } // 开启深度监听，因为数组内部元素的变化需要被检测到  
  ); 
  
  </script>
  
  <style scoped>
  /* 这里可以添加一些样式，如果需要的话 */
  </style>